<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>函数的部分执行</title>
</head>
<body>
    <h1>函数的部分执行</h1>
    <h2>允许只传入函数的部分参数</h2>

    <script>
        // 目前的写法
        function add(x, y) {
            return x + y;
        }
        const addOne = x => add(1, x);

        // 部分执行提案的写法
        /*
        const addOne = add(1, ?);
        const addTen = add(?, 10);
        */

        // 实际应用示例
        // 1. 模拟部分执行
        function partial(fn, ...args) {
            return function(...restArgs) {
                const fullArgs = args.map(arg => 
                    arg === undefined ? restArgs.shift() : arg
                );
                return fn.apply(this, [...fullArgs, ...restArgs]);
            };
        }

        // 使用示例
        function multiply(a, b, c) {
            return a * b * c;
        }

        const multiplyByTwo = partial(multiply, 2, undefined, undefined);
        console.log(multiplyByTwo(3, 4)); // 24

        // 2. 柯里化实现
        function curry(fn) {
            return function curried(...args) {
                if (args.length >= fn.length) {
                    return fn.apply(this, args);
                }
                return function(...args2) {
                    return curried.apply(this, args.concat(args2));
                };
            };
        }

        const curriedMultiply = curry(multiply);
        console.log(curriedMultiply(2)(3)(4)); // 24

        // 3. 实际应用场景
        class QueryBuilder {
            constructor(table) {
                this.table = table;
                this.conditions = [];
            }

            where(field, operator, value) {
                this.conditions.push({ field, operator, value });
                return this;
            }

            build() {
                const where = this.conditions
                    .map(c => `${c.field} ${c.operator} ${c.value}`)
                    .join(' AND ');
                return `SELECT * FROM ${this.table} WHERE ${where}`;
            }
        }

        const createQuery = partial(
            (table, field, value) => 
                new QueryBuilder(table)
                    .where(field, '=', value)
                    .build(),
            'users'
        );

        console.log(createQuery('name', "'John'")); 
        // "SELECT * FROM users WHERE name = 'John'"
    </script>
</body>
</html> 